#include "executor.h"

#include <Windows.h>

Executor::Executor(QObject *parent) : QObject(parent)
{
    links = initDir("links");

    qDebug() << links->absolutePath();
}

Executor::~Executor()
{
    delete links;
}

QDir *Executor::initDir(const QString &path)
{
    QDir *dir = new QDir{"."};

    if(!dir->cd(path))
    {
        if(!dir->mkdir(path))
        {
            delete dir;
            return nullptr;
        }
        dir->cd(path);
    }
    return dir;
}

void Executor::run(const QString &command)
{
    QString path = links->absolutePath() + "/" +
                   command + ".lnk";
    absoluteExecute(path);

}


bool Executor::execute(const QString &command)
{
    if (command.startsWith(QChar(':')))
    {
        emit executeInnerAction(command);
    }
    else if(command.startsWith(QChar(',')))
    {
        QString runningProg = command.right(command.count()-1);
        qDebug() << runningProg << command;
        system(runningProg.toStdString().c_str());
    }
    else if(links->exists(command + ".lnk"))
    {
        qDebug() << "starting " << command;
        run(command);
    }
    else
    {
        qDebug() << "cannot find " << command;
        return false;
    }
    return true;
}

void Executor::absoluteExecute(const QString &path)
{

    qDebug() << "starting:" << path;

    LPCWSTR program = path.toStdWString().c_str();

    ShellExecute(nullptr, nullptr,
                 program,
                 nullptr, nullptr,
                 SW_SHOWNORMAL);
//    QProcess::startDetached(path);
}

QString Executor::linksDir()
{
    return links->absolutePath() + "/";
}

void Executor::reload()
{
    linkList.clear();
    links->refresh();
    QStringList tmpLinkList = links->entryList(QDir::Filter::AllEntries|QDir::Filter::NoDot|QDir::Filter::NoDotDot,QDir::Name);
    foreach(QString item, tmpLinkList)
    {
        linkList.append(item.left(item.lastIndexOf('.')));
    }

    qDebug()<<linkList;
}


